﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using HotShot.Service.Entities;
using HotShot.Entities.Messages;

namespace HotShot.Service.BusinessLogic.Worker
{
    /// <summary>
    /// Worker for processing timed-out, not fully correlated messages
    /// </summary>
    public class CorrelationResultWorker: WorkerBase
    {
        protected override Guid ProcessorId
        {
            get { return Guid.NewGuid(); }
        }

        Dictionary<string, int> MessageThresholds = new Dictionary<string, int>();

        public override void Initialize(string executorMachineName, string processorName, int periodicityMilliSec)
        {
            base.Initialize(executorMachineName, processorName, periodicityMilliSec);
            MessageThresholds.Add("RetrieveResultInternal", MessagingLogic.Current.RetrieveThreshold);
            MessageThresholds.Add("StoreResult", MessagingLogic.Current.StoreThreshold);
        }

        protected override bool Work()
        {
            foreach (var mt in MessageThresholds)
            {
                foreach (var correlatedMessage in MessageCorrelationLogic.Current.CollectAvailableResults(mt.Key, mt.Value))
                {
                    MessagingLogic.Current.ProcessMessage(
                        correlatedMessage.Responses.Select(i => i.Value).FirstOrDefault(i => i != null),
                        correlatedMessage.CorrelationId,
                        false);
                }
            }

            return false;
        }
    }
}
